﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using AuroraLightsFX.Properties;
using Microsoft.Win32;
using System.IO;
using System.Threading;
using System.Resources;
using System.Diagnostics;

namespace AuroraLightsFX
{
    public partial class AuroraLightsFX : Form
    {

        NotifyIcon sysTrayHandler = new NotifyIcon();
        AsyncRegMon regMon = new AsyncRegMon(RegistryHive.CurrentUser, Program._RegKey + "\\Colors");
        ContextMenu contextMenu = new ContextMenu();

        MenuItem mnuRandomColors = new MenuItem("&Random Colors");
        MenuItem mnuApplyToAll = new MenuItem("Apply &same color to all");
        MenuItem mnuColorChoose = new MenuItem("Select Custom Color");

        MenuItem mnuColorRed = new MenuItem("Red");
        MenuItem mnuColorBlue = new MenuItem("Blue");
        MenuItem mnuColorGreen = new MenuItem("Green");
        MenuItem mnuColorWhite = new MenuItem("White");
        MenuItem mnuColorYellow = new MenuItem("Yellow");
        MenuItem mnuColorMagenta = new MenuItem("Magenta");
        MenuItem mnuColorCyan = new MenuItem("Cyan");
        MenuItem mnuColorOrange = new MenuItem("Orange");
        MenuItem mnuColorPink = new MenuItem("Pink");
        MenuItem mnuColorSeperator = new MenuItem("-");
        MenuItem mnuColorTurnOff = new MenuItem("Turn Off Lights");
        
        MenuItem mnuOptions = new MenuItem("&Options");
        MenuItem mnuLoadOnStartup = new MenuItem("Load on &startup");
        MenuItem mnuMonitorWallpaper = new MenuItem("Monitor &Wallpaper");
        MenuItem mnuExit = new MenuItem("E&xit");

        public AuroraLightsFX()
        {
            InitializeComponent();
            LoadSettings();

        }



        void AuroraLightsFX_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            if (e.CloseReason == System.Windows.Forms.CloseReason.ApplicationExitCall)
                sysTrayHandler.Dispose();
            else if (e.CloseReason == System.Windows.Forms.CloseReason.UserClosing)
            {
                this.WindowState = FormWindowState.Minimized;
                e.Cancel = true;
            }

        }


        void AuroraLightsFX_Shown(object sender, System.EventArgs e)
        {
            if (Program.StartUpMode)
                this.Visible = false;
            else
            {
                this.WindowState = FormWindowState.Normal;
                this.ShowInTaskbar = true;
                this.Visible = true;
            }
        }

        void mnuExit_Click(object sender, EventArgs e)
        {
            sysTrayHandler.Visible = false;
            Application.Exit();
        }

       

        void mnuRandomColors_Click(object sender, EventArgs e)
        {

            // 6/25/09: Vikas Verma
            // If user change the color manually then ideally we should stop monitoring the wallpaper to change the colors
            chkWallpaper.Checked = false;
            

            Random random = new Random();


            if (chkSystemTypeLaptop.Checked)
            {
                lblAlienHead.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblAlienName.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblKeyboard.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblLightPipe.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblMouse.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblTouchPanel.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblPowerButton.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
            }
            else
            {
                lblAlienEyes.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblBottomGills.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblFrontBays.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblFrontIO.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblFrontUSB.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblLeftAlienHead.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblMiddleGills.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblPowerRim.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblRightAlienHead.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
                lblTopGills.BackColor = Color.FromArgb(random.Next(1, 255), random.Next(1, 255), random.Next(1, 255)); ;
            }


            btnApply_Click(null, null);
            SaveSettings();
        }

        void mnuMonitorWallpaper_Click(object sender, EventArgs e)
        {
            Program.WallPaperMode = !Program.WallPaperMode;
            chkWallpaper.Checked = Program.WallPaperMode;
        }

        void mnuLoadOnStartup_Click(object sender, EventArgs e)
        {
            chkStartup.Checked = !chkStartup.Checked;
        }




        void SetWallPaperColor()
        {

            Color clr = GetWallPaperColor();

            if (chkSystemTypeLaptop.Checked)
            {
                lblAlienHead.BackColor = clr;
                lblAlienName.BackColor = clr;
                lblKeyboard.BackColor = clr;
                lblLightPipe.BackColor = clr;
                lblMouse.BackColor = clr;
                lblTouchPanel.BackColor = clr;
                lblPowerButton.BackColor = clr;
            }
            else
            {
                lblAlienEyes.BackColor = clr;
                lblBottomGills.BackColor = clr;
                lblFrontBays.BackColor = clr;
                lblFrontIO.BackColor = clr;
                lblFrontUSB.BackColor = clr;
                lblLeftAlienHead.BackColor = clr;
                lblMiddleGills.BackColor = clr;
                lblPowerRim.BackColor = clr;
                lblRightAlienHead.BackColor = clr;
                lblTopGills.BackColor = clr;
            }

            //FOR LAPTOP
            LedController.LedSetting[] LaptopSettings = new LedController.LedSetting[] { 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting()};

            //FOR DESKTOP
            LedController.LedSetting[] DesktopSettings = new LedController.LedSetting[] { 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting()
            };

            LaptopSettings[0] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.AlienHead), lblAlienHead.BackColor);
            LaptopSettings[1] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.AlienName), lblAlienName.BackColor);
            LaptopSettings[2] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.Keyboard), lblKeyboard.BackColor);
            LaptopSettings[3] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.LightPipe), lblLightPipe.BackColor);
            LaptopSettings[4] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.TouchPanel), lblTouchPanel.BackColor);
            LaptopSettings[5] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.Mouse), lblMouse.BackColor);
            LaptopSettings[6] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.Mouse), lblMouse.BackColor);

            DesktopSettings[0] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.BottomGills), lblBottomGills.BackColor);
            DesktopSettings[1] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.MiddleGills), lblMiddleGills.BackColor);
            DesktopSettings[2] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.FrontUSB), lblFrontUSB.BackColor);
            DesktopSettings[3] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.PowerRim), lblPowerRim.BackColor);
            DesktopSettings[4] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.TopGills), lblTopGills.BackColor);
            DesktopSettings[5] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.FrontIO), lblFrontIO.BackColor);
            DesktopSettings[6] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.AlienEyes), lblAlienEyes.BackColor);
            DesktopSettings[7] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.LeftAlienHead), lblLeftAlienHead.BackColor);
            DesktopSettings[8] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.RightAlienHead), lblRightAlienHead.BackColor);
            DesktopSettings[9] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.FrontBays), lblFrontBays.BackColor);

            //// TODO : I was testing morphing here
            //////////LedController.LedSetting[] settings = LedController.CreateSetting(LedController.GetLed(LedController.LedName.Keyboard), Color.Red, Color.Green);
            //////////LedController.LedSetting[] settings = new LedController.LedSetting[] { new LedController.LedSetting(), new LedController.LedSetting()};
            //////////settings[0] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.Keyboard), Color.Red);
            //////////settings[0].duration = 0;
            //////////settings[1] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.Keyboard), Color.Blue);
            //////////settings[1].duration = 0;

            if (chkSystemTypeLaptop.Checked)
                LedController.SetColor(LaptopSettings);
            else
                LedController.SetColor(DesktopSettings);

        }

        public Label picBox = null;

        void colorSelector_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && e.X >= 0 && e.Y >= 0)
            {
                Bitmap bmp = new Bitmap(colorSelector.Image);

                if (e.X < bmp.Width && e.Y < bmp.Height)
                {
                    Color clr = bmp.GetPixel(e.X, e.Y);

                    if (picBox != null)
                        picBox.BackColor = clr;
                }
            }
        }


        void BoxClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (sender == null)
                return;

            picBox = (Label)sender;
        }



        void AuroraLightsFX_Resize(object sender, System.EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
                this.Visible = false;
                try
                {
                    if ((int)Registry.CurrentUser.CreateSubKey(Program._RegKey + "\\Settings").GetValue("ShowSysTrayBalloon") == 1)
                        sysTrayHandler.ShowBalloonTip(1000);
                }
                catch
                {
                    sysTrayHandler.ShowBalloonTip(1000);
                }
            }
            else
            {
                if (!this.ShowInTaskbar) this.ShowInTaskbar = true;
                if (!this.Visible) this.Visible = true;
            }
        }

        ////// To monitor wallpaper changed event
        ////protected override void DefWndProc(ref Message m)
        ////{

        ////    const UInt32 SPI_SETDESKWALLPAPER = 0x14;
        ////    const UInt32 WM_SETTINGCHANGE     = 0x1A;


        ////    if (m.Msg == WM_SETTINGCHANGE)
        ////    {
        ////        if (m.WParam.ToInt32() == SPI_SETDESKWALLPAPER)
        ////            MessageBox.Show("Wallpaper Changed");
        ////    }



        ////    base.DefWndProc(ref m);
        ////}
        void sysTrayHandler_BalloonTipClicked(object sender, EventArgs e)
        {
            Registry.CurrentUser.CreateSubKey(Program._RegKey + "\\Settings").SetValue("ShowSysTrayBalloon", 0);
        }

        void sysTrayHandler_DoubleClick(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;

        }


        private void btnApply_Click(object sender, EventArgs e)
        {
            btnApply.Enabled = false;
            btnApply.Text = "Wait...";


            //FOR LAPTOP
            LedController.LedSetting[] LaptopSettings = new LedController.LedSetting[] { 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting()};

            //FOR DESKTOP
            LedController.LedSetting[] DesktopSettings = new LedController.LedSetting[] { 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting(), 
                    new LedController.LedSetting()
            };

            LaptopSettings[0] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.AlienHead), lblAlienHead.BackColor);
            LaptopSettings[1] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.AlienName), lblAlienName.BackColor);
            LaptopSettings[2] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.Keyboard), lblKeyboard.BackColor);
            LaptopSettings[3] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.LightPipe), lblLightPipe.BackColor);
            LaptopSettings[4] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.TouchPanel), lblTouchPanel.BackColor);
            LaptopSettings[5] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.Mouse), lblMouse.BackColor);
            LaptopSettings[6] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.Mouse), lblMouse.BackColor);

            DesktopSettings[0] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.BottomGills), lblBottomGills.BackColor);
            DesktopSettings[1] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.MiddleGills), lblMiddleGills.BackColor);
            DesktopSettings[2] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.FrontUSB), lblFrontUSB.BackColor);
            DesktopSettings[3] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.PowerRim), lblPowerRim.BackColor);
            DesktopSettings[4] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.TopGills), lblTopGills.BackColor);
            DesktopSettings[5] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.FrontIO), lblFrontIO.BackColor);
            DesktopSettings[6] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.AlienEyes), lblAlienEyes.BackColor);
            DesktopSettings[7] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.LeftAlienHead), lblLeftAlienHead.BackColor);
            DesktopSettings[8] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.RightAlienHead), lblRightAlienHead.BackColor);
            DesktopSettings[9] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.FrontBays), lblFrontBays.BackColor);

            //// TODO : I was testing morphing here
            //////////LedController.LedSetting[] settings = LedController.CreateSetting(LedController.GetLed(LedController.LedName.Keyboard), Color.Red, Color.Green);
            //////////LedController.LedSetting[] settings = new LedController.LedSetting[] { new LedController.LedSetting(), new LedController.LedSetting()};
            //////////settings[0] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.Keyboard), Color.Red);
            //////////settings[0].duration = 0;
            //////////settings[1] = LedController.CreateSetting(LedController.GetLed(LedController.LedName.Keyboard), Color.Blue);
            //////////settings[1].duration = 0;

            bool boolSuccess= false;

            if (chkSystemTypeLaptop.Checked)
                boolSuccess = LedController.SetColor(LaptopSettings);
            else
                boolSuccess = LedController.SetColor(DesktopSettings);

            if (!boolSuccess)
            MessageBox.Show("Unable to set colors, it could be due to hardware problem.\nMake sure your AlienFX Board is working properly", Application.ProductName);
            

            btnApply.Enabled = true;
            btnApply.Text = "Apply";

            if (sender != null)
            {
                // 6/25/09: Vikas Verma
                // If user change the color manually then ideally we should stop monitoring the wallpaper to change the colors
                chkWallpaper.Checked = false;
            

                SaveSettings();
            }
        }

        void LoadSettings()
        {
            string cmdline = string.Empty;
            try
            {
                cmdline = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run").GetValue("AuroraLightsFX").ToString();
            }
            catch { }
            if (!string.IsNullOrEmpty(cmdline))
            {
                if (cmdline.EndsWith("/startup"))
                    chkStartup.Checked = true;
            }

            RegistryKey regSettings = null;

            regSettings = Registry.CurrentUser.CreateSubKey(Program._RegKey + "\\Colors");
            lblAlienHead.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._AlienHead, Color.White.ToArgb()));
            lblAlienName.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._AlienName, Color.White.ToArgb()));
            lblKeyboard.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._Keyboard, Color.White.ToArgb()));
            lblLightPipe.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._LightPipe, Color.White.ToArgb()));
            lblMouse.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._Mouse, Color.White.ToArgb()));
            lblTouchPanel.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._TouchPanel, Color.White.ToArgb()));
            lblPowerButton.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._PowerButton, Color.White.ToArgb()));
            lblBottomGills.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._BottomGills, Color.White.ToArgb()));
            lblMiddleGills.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._MiddleGills, Color.White.ToArgb()));
            lblFrontUSB.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._FrontUSB, Color.White.ToArgb()));
            lblPowerRim.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._PowerRim, Color.White.ToArgb()));
            lblTopGills.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._TopGills, Color.White.ToArgb()));
            lblFrontIO.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._FrontIO, Color.White.ToArgb()));
            lblAlienEyes.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._AlienEyes, Color.White.ToArgb()));
            lblLeftAlienHead.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._LeftAlienHead, Color.White.ToArgb()));
            lblRightAlienHead.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._RightAlienHead, Color.White.ToArgb()));
            lblFrontBays.BackColor = Color.FromArgb((int)regSettings.GetValue(Program._FrontBays, Color.White.ToArgb()));
            regSettings.Close();


            try
            {
                regSettings = Registry.CurrentUser.CreateSubKey(Program._RegKey + "\\Settings");
                Program.WallPaperMode = bool.Parse(regSettings.GetValue("MonitorWallpaper").ToString());
                chkSystemTypeLaptop.Checked = bool.Parse(regSettings.GetValue(Program._IsSystemTypeLaptop, true).ToString());
                chkSystemTypeDesktop.Checked = !chkSystemTypeLaptop.Checked;
                regSettings.Close();
                regSettings = null;
            }
            catch { }

            

            this.Icon = Resources.AlienIcon;
            sysTrayHandler.Icon = this.Icon;

            if (File.Exists(Application.ExecutablePath + ".ico"))
                sysTrayHandler.Icon = new Icon(Application.ExecutablePath + ".ico");
            
            sysTrayHandler.Visible = true;
            sysTrayHandler.ContextMenu = contextMenu;

            mnuOptions.MenuItems.Add(mnuLoadOnStartup);
            mnuOptions.MenuItems.Add(mnuMonitorWallpaper);

            mnuApplyToAll.MenuItems.Add(mnuColorChoose);
            mnuApplyToAll.MenuItems.Add(mnuColorTurnOff);
            mnuApplyToAll.MenuItems.Add(mnuColorSeperator);
            mnuApplyToAll.MenuItems.Add(mnuColorBlue);
            mnuApplyToAll.MenuItems.Add(mnuColorCyan);
            mnuApplyToAll.MenuItems.Add(mnuColorGreen);
            mnuApplyToAll.MenuItems.Add(mnuColorMagenta);
            mnuApplyToAll.MenuItems.Add(mnuColorOrange);
            mnuApplyToAll.MenuItems.Add(mnuColorPink);
            mnuApplyToAll.MenuItems.Add(mnuColorRed);
            mnuApplyToAll.MenuItems.Add(mnuColorWhite);
            mnuApplyToAll.MenuItems.Add(mnuColorYellow);


            mnuColorTurnOff.Tag = Color.Black;
            mnuColorBlue.Tag = Color.Blue;
            mnuColorCyan.Tag = Color.Cyan;
            mnuColorGreen.Tag = Color.Green;
            mnuColorMagenta.Tag = Color.Magenta;
            mnuColorOrange.Tag = Color.Orange;
            mnuColorPink.Tag = Color.HotPink;
            mnuColorRed.Tag = Color.Red;
            mnuColorWhite.Tag = Color.White;
            mnuColorYellow.Tag = Color.Yellow;


            contextMenu.MenuItems.Add(mnuRandomColors);
            contextMenu.MenuItems.Add(mnuApplyToAll);
            contextMenu.MenuItems.Add(mnuOptions);
            contextMenu.MenuItems.Add(mnuExit);


            mnuApplyToAll.MenuItems.Add(mnuColorChoose);
            mnuApplyToAll.MenuItems.Add(mnuColorTurnOff);
            mnuApplyToAll.MenuItems.Add(mnuColorSeperator);
            mnuApplyToAll.MenuItems.Add(mnuColorBlue);
            mnuApplyToAll.MenuItems.Add(mnuColorCyan);
            mnuApplyToAll.MenuItems.Add(mnuColorGreen);
            mnuApplyToAll.MenuItems.Add(mnuColorMagenta);
            mnuApplyToAll.MenuItems.Add(mnuColorOrange);
            mnuApplyToAll.MenuItems.Add(mnuColorPink);
            mnuApplyToAll.MenuItems.Add(mnuColorRed);
            mnuApplyToAll.MenuItems.Add(mnuColorWhite);
            mnuApplyToAll.MenuItems.Add(mnuColorYellow);


            mnuColorTurnOff.Click += new EventHandler(mnuColorChoose_Click);
            mnuColorBlue.Click += new EventHandler(mnuColorChoose_Click);
            mnuColorCyan.Click += new EventHandler(mnuColorChoose_Click);
            mnuColorGreen.Click += new EventHandler(mnuColorChoose_Click);
            mnuColorMagenta.Click += new EventHandler(mnuColorChoose_Click);
            mnuColorOrange.Click += new EventHandler(mnuColorChoose_Click);
            mnuColorPink.Click += new EventHandler(mnuColorChoose_Click);
            mnuColorRed.Click += new EventHandler(mnuColorChoose_Click);
            mnuColorWhite.Click += new EventHandler(mnuColorChoose_Click);
            mnuColorYellow.Click += new EventHandler(mnuColorChoose_Click);
            

            mnuRandomColors.Click += new EventHandler(mnuRandomColors_Click);
            mnuColorChoose.Click += new EventHandler(mnuColorChoose_Click);
            mnuLoadOnStartup.Click += new EventHandler(mnuLoadOnStartup_Click);
            mnuMonitorWallpaper.Click += new EventHandler(mnuMonitorWallpaper_Click);
            mnuExit.Click += new EventHandler(mnuExit_Click);

            sysTrayHandler.BalloonTipIcon = ToolTipIcon.Info;
            sysTrayHandler.BalloonTipText = "I am still running :)";
            sysTrayHandler.BalloonTipTitle = Application.ProductName;
            sysTrayHandler.DoubleClick += new EventHandler(sysTrayHandler_DoubleClick);
            sysTrayHandler.BalloonTipClicked += new EventHandler(sysTrayHandler_BalloonTipClicked);

            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
            {
                System.Deployment.Application.ApplicationDeployment ad = System.Deployment.Application.ApplicationDeployment.CurrentDeployment;
                this.Text = Application.ProductName + " - " + ad.CurrentVersion;
            }

            mnuLoadOnStartup.Checked = chkStartup.Checked;
            chkWallpaper.Checked = Program.WallPaperMode;
            mnuMonitorWallpaper.Checked = Program.WallPaperMode;

        }

        void mnuColorChoose_Click(object sender, EventArgs e)
        {
            // 6/25/09: Vikas Verma
            // If user change the color manually then ideally we should stop monitoring the wallpaper to change the colors
            chkWallpaper.Checked = false;
            

            Color myColor = Color.Black;

            if (((MenuItem)sender) == mnuColorChoose)
            {
                colorDialog1.ShowDialog();
                myColor = colorDialog1.Color;
            }
            else
            {
                myColor = (Color)((MenuItem)sender).Tag;
            }


                if (chkSystemTypeLaptop.Checked)
                {
                    lblAlienHead.BackColor = myColor;
                    lblAlienName.BackColor = myColor;
                    lblKeyboard.BackColor = myColor;
                    lblLightPipe.BackColor = myColor;
                    lblMouse.BackColor = myColor;
                    lblTouchPanel.BackColor = myColor;
                    lblPowerButton.BackColor = myColor;
                }
                else
                {
                    lblAlienEyes.BackColor = myColor;
                    lblBottomGills.BackColor = myColor;
                    lblFrontBays.BackColor = myColor;
                    lblFrontIO.BackColor = myColor;
                    lblFrontUSB.BackColor = myColor;
                    lblLeftAlienHead.BackColor = myColor;
                    lblMiddleGills.BackColor = myColor;
                    lblPowerRim.BackColor = myColor;
                    lblRightAlienHead.BackColor = myColor;
                    lblTopGills.BackColor = myColor;
                }
            btnApply_Click(null, null);
            SaveSettings();

        }

        void SaveSettings()
        {

            // If wallpaper mode is not set , then we will monitor our registry settings for any change
            // This helps any third party application to change the registry value and being able to change the color
            // We stop the monitor if we are monitoring self keys, to prevent a circular loop 
            if (!Program.WallPaperMode)
                regMon.Stop();

            RegistryKey regSettings = Registry.CurrentUser.CreateSubKey(Program._RegKey + "\\Colors");
            regSettings.SetValue(Program._AlienHead, lblAlienHead.BackColor.ToArgb());
            regSettings.SetValue(Program._AlienName, lblAlienName.BackColor.ToArgb());
            regSettings.SetValue(Program._Keyboard, lblKeyboard.BackColor.ToArgb());
            regSettings.SetValue(Program._LightPipe, lblLightPipe.BackColor.ToArgb());
            regSettings.SetValue(Program._Mouse, lblMouse.BackColor.ToArgb());
            regSettings.SetValue(Program._TouchPanel, lblTouchPanel.BackColor.ToArgb());

            regSettings.SetValue(Program._PowerButton, lblPowerButton.BackColor.ToArgb());
            regSettings.SetValue(Program._BottomGills, lblBottomGills.BackColor.ToArgb());
            regSettings.SetValue(Program._MiddleGills, lblMiddleGills.BackColor.ToArgb());
            regSettings.SetValue(Program._FrontUSB, lblFrontUSB.BackColor.ToArgb());
            regSettings.SetValue(Program._PowerRim, lblPowerRim.BackColor.ToArgb());
            regSettings.SetValue(Program._TopGills, lblTopGills.BackColor.ToArgb());
            regSettings.SetValue(Program._FrontIO, lblFrontIO.BackColor.ToArgb());
            regSettings.SetValue(Program._AlienEyes, lblAlienEyes.BackColor.ToArgb());
            regSettings.SetValue(Program._LeftAlienHead, lblLeftAlienHead.BackColor.ToArgb());
            regSettings.SetValue(Program._RightAlienHead, lblRightAlienHead.BackColor.ToArgb());
            regSettings.SetValue(Program._FrontBays, lblFrontBays.BackColor.ToArgb());


            regSettings.Flush();
            regSettings.Close();
            regSettings = null;

            regSettings = Registry.CurrentUser.CreateSubKey(Program._RegKey + "\\Settings");
            regSettings.SetValue(Program._IsSystemTypeLaptop, chkSystemTypeLaptop.Checked);
            regSettings.Flush();
            regSettings.Close();
            regSettings = null;

            // If we were not monitoring wallpaper then we need to start the monitor again which we stopped initially
            if (!Program.WallPaperMode)
                regMon.Start();

        }


        void regMon_RegChanged(object sender, EventArgs e)
        {

            if (Program.WallPaperMode)
                SetWallPaperColor();
            else
            {
                RegistryKey regSettings = Registry.CurrentUser.CreateSubKey(Program._RegKey + "\\Colors");

                List<LedController.LedSetting> settings = new List<LedController.LedSetting>();

                if (Program.clrAlienHead != Color.FromArgb((int)regSettings.GetValue(Program._AlienHead, Color.Black.ToArgb())))
                {
                    Program.clrAlienHead = Color.FromArgb((int)regSettings.GetValue(Program._AlienHead, Color.Black.ToArgb()));
                    settings.Add(LedController.CreateSetting(LedController.GetLed(LedController.LedName.AlienHead), Program.clrAlienHead));
                }

                if (Program.clrAlienName != Color.FromArgb((int)regSettings.GetValue(Program._AlienName, Color.Black.ToArgb())))
                {
                    Program.clrAlienName = Color.FromArgb((int)regSettings.GetValue(Program._AlienName, Color.Black.ToArgb()));
                    settings.Add(LedController.CreateSetting(LedController.GetLed(LedController.LedName.AlienName), Program.clrAlienName));
                }

                if (Program.clrKeyboard != Color.FromArgb((int)regSettings.GetValue(Program._Keyboard, Color.Black.ToArgb())))
                {
                    Program.clrKeyboard = Color.FromArgb((int)regSettings.GetValue(Program._Keyboard, Color.Black.ToArgb()));
                    settings.Add(LedController.CreateSetting(LedController.GetLed(LedController.LedName.Keyboard), Program.clrKeyboard));
                }

                if (Program.clrLightPipe != Color.FromArgb((int)regSettings.GetValue(Program._LightPipe, Color.Black.ToArgb())))
                {
                    Program.clrLightPipe = Color.FromArgb((int)regSettings.GetValue(Program._LightPipe, Color.Black.ToArgb()));
                    settings.Add(LedController.CreateSetting(LedController.GetLed(LedController.LedName.LightPipe), Program.clrLightPipe));
                }

                if (Program.clrMouse != Color.FromArgb((int)regSettings.GetValue(Program._Mouse, Color.Black.ToArgb())))
                {
                    Program.clrMouse = Color.FromArgb((int)regSettings.GetValue(Program._Mouse, Color.Black.ToArgb()));
                    settings.Add(LedController.CreateSetting(LedController.GetLed(LedController.LedName.Mouse), Program.clrMouse));
                }

                if (Program.clrTouchPanel != Color.FromArgb((int)regSettings.GetValue(Program._TouchPanel, Color.Black.ToArgb())))
                {
                    Program.clrTouchPanel = Color.FromArgb((int)regSettings.GetValue(Program._TouchPanel, Color.Black.ToArgb()));
                    settings.Add(LedController.CreateSetting(LedController.GetLed(LedController.LedName.TouchPanel), Program.clrTouchPanel));
                }


                LedController.SetColor(settings.ToArray());

                regSettings.Close();
                regSettings = null;
            }
        }

        void regMon_Error(object sender, ErrorEventArgs e)
        {
            MessageBox.Show(e.GetException().ToString());
            //regMon.Stop();
            //regMon.Start();
        }

        private void chkStartup_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (chkStartup.Checked)
                {
                    Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run").SetValue("AuroraLightsFX", Application.ExecutablePath + " /startup");
                }
                else
                    Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true).DeleteValue("AuroraLightsFX");
            }
            catch { }

            mnuLoadOnStartup.Checked = chkStartup.Checked;
        }

        void RGB_Input(object sender, System.EventArgs e)
        {
            if (picBox == null || sender == null)
                return;

            picBox = (Label)sender;
            colorDialog1.ShowDialog();
            picBox.BackColor = colorDialog1.Color;

            if (picBox.BackColor == Color.Black)
                picBox.ForeColor = Color.White;
            else
                picBox.ForeColor = Color.Black;

        }

        private void chkWallpaper_CheckedChanged(object sender, EventArgs e)
        {

            // We need to verify sender as we are calling this function from mnuMonitorWallpaper_Click to toggle its state
            // but does not actually want to execute the code in that case
            Program.WallPaperMode = chkWallpaper.Checked;
            mnuMonitorWallpaper.Checked = Program.WallPaperMode; 
            ToggleWallpaperSettings();
                
        }

        private void ToggleWallpaperSettings()
        {

            try
            {
                if (Program.WallPaperMode)
                {
                    Color clr = GetWallPaperColor();


                    if (chkSystemTypeLaptop.Checked)
                    {
                        lblAlienHead.BackColor = clr;
                        lblAlienName.BackColor = clr;
                        lblKeyboard.BackColor = clr;
                        lblLightPipe.BackColor = clr;
                        lblMouse.BackColor = clr;
                        lblTouchPanel.BackColor = clr;
                        lblPowerButton.BackColor = clr;
                    }
                    else
                    {
                        lblAlienEyes.BackColor = clr;
                        lblBottomGills.BackColor = clr;
                        lblFrontBays.BackColor = clr;
                        lblFrontIO.BackColor = clr;
                        lblFrontUSB.BackColor = clr;
                        lblLeftAlienHead.BackColor = clr;
                        lblMiddleGills.BackColor = clr;
                        lblPowerRim.BackColor = clr;
                        lblRightAlienHead.BackColor = clr;
                        lblTopGills.BackColor = clr;
                    }

                    btnApply_Click(null, null);

                }

                SaveSettings();
                    
                RegistryKey regSettings = Registry.CurrentUser.CreateSubKey(Program._RegKey + "\\Settings");
                regSettings.SetValue("MonitorWallpaper", Program.WallPaperMode);
                regSettings.Close();
                regSettings = null;
            }
            catch { }

            if (regMon != null)
            {
                if (regMon.IsMonitoring)
                    regMon.Stop();
            }

            if (Program.WallPaperMode)
                regMon = new AsyncRegMon(RegistryHive.CurrentUser, "Control Panel\\Desktop");
            else
                regMon = new AsyncRegMon(RegistryHive.CurrentUser, Program._RegKey + "\\Colors");

            regMon.Start();
            regMon.RegChanged += new EventHandler(regMon_RegChanged);
            regMon.Error += new ErrorEventHandler(regMon_Error);

        }

        Color GetWallPaperColor()
        {
            //return Color.Black;
            
            string fileName = string.Empty;
            try
            {
                fileName = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop").GetValue("Wallpaper").ToString();
            }
            catch { }

            if (!File.Exists(fileName))
                return Color.White;

            Thread.Sleep(500);
            Bitmap bmWallpaper = new Bitmap(fileName);
            int totalPixels = bmWallpaper.Width * bmWallpaper.Height;
            int totalRed = 0;
            int totalGreen = 0;
            int totalBlue = 0;

            for (int x = 0; x < bmWallpaper.Width; x++)
            {
                for (int y = 0; y < bmWallpaper.Height; y++)
                {
                    Color rgb = bmWallpaper.GetPixel(x, y);
                    totalRed += rgb.R;
                    totalGreen += rgb.G;
                    totalBlue += rgb.B;
                }
            }
            
            Color average = Color.FromArgb(totalRed / totalPixels, totalGreen / totalPixels, totalBlue / totalPixels);
            bmWallpaper.Dispose();
            bmWallpaper = null;

            return average;




        }


        private void SystemTypeChanged(object sender, EventArgs e)
        {
            grpLaptop.Visible = chkSystemTypeLaptop.Checked;
            grpDesktop.Visible = chkSystemTypeDesktop.Checked;
        }

        void LabelColorChanged(object sender, System.EventArgs e)
        {

            if (sender == null)
                return;

            Label tmpLabel = (Label)sender;

            //pull each colour component and flip it (compiler demanded the cast)
            byte bRed = (byte)~(tmpLabel.BackColor.R);
            byte bGreen = (byte)~(tmpLabel.BackColor.G);
            byte bBlue = (byte)~(tmpLabel.BackColor.B);
            //set the text colour with overload of Argb
            tmpLabel.ForeColor = Color.FromArgb(bRed, bGreen, bBlue);

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("http://forum.notebookreview.com/showthread.php?t=307050");
        }










    }
}
